package com.ww.java17;

public class SwitchDemo {
    /**
     * 正如instanceof一样，switch也紧跟着增加了类型匹配自动转换功能
     */
    // Old code
    static String formatter(Object o) {
        String formatted = "unknown";
        if (o instanceof Integer i) {
            formatted = String.format("int %d", i);
        } else if (o instanceof Long l) {
            formatted = String.format("long %d", l);
        } else if (o instanceof Double d) {
            formatted = String.format("double %f", d);
        } else if (o instanceof String s) {
            formatted = String.format("String %s", s);
        }
        return formatted;
    }

    // New code
    static String formatterPatternSwitch(Object o) {
        return switch (o) {
            case Integer i -> String.format("int %d", i); // 这种写法省略了break
            case Long l -> String.format("long %d", l);
            case Double d -> String.format("double %f", d);
            case String s -> String.format("String %s", s);
            default -> o.toString();
        };
    }

    /**
     * 返回值不再需要break
     *
     * @param fruit
     */
    static void withReturnValue(Fruit fruit) {
        String text = switch (fruit) {
            case APPLE, PEAR -> "普通水果";
            case MANGO, AVOCADO -> "进口水果";
            default -> "未知水果";
        };
        System.out.println(text);
    }

    static void withSwitchExpression(Fruit fruit) {
        System.out.println(switch (fruit) {
            case APPLE, PEAR -> "普通水果";
            case MANGO, AVOCADO -> "进口水果";
            default -> "未知水果";
        });
    }

    // 如果你想在case里想做不止一件事，比如在返回之前先进行一些计算或者打印操作，可以通过
    // 大括号来作为case块，最后的返回值使用关键字yield进行返回
    static void withYield(Fruit fruit) {
        String text = switch (fruit) {
            case APPLE, PEAR -> {
                System.out.println("给的水果是：" + fruit);
                yield "普通水果";
            }
            case MANGO, AVOCADO -> "进口水果";
            default -> "未知水果";
        };
        System.out.println(text);
    }

    // 也可以直接使用yield返回结果
    static void oldStyleWithYield(Fruit fruit) {
        System.out.println(switch (fruit) {
            case APPLE, PEAR:
                yield "普通水果";
            case MANGO, AVOCADO:
                yield "进口水果";
            default:
                yield "未知水果";
        });
    }

    public static void main(String[] args) {
        Double d = (Double) 3.14159;
        System.out.println(formatter(d));
        System.out.println(formatterPatternSwitch(d));

        withReturnValue(Fruit.APPLE);
        withSwitchExpression(Fruit.AVOCADO);
        withYield(Fruit.PEACH);
    }
}
